package one.bugu.android.demon.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.MedalBean;
import one.bugu.android.demon.bean.UserSmsInfoBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseFragment;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.constant.MedalContant;
import one.bugu.android.demon.ui.activity.*;
import one.bugu.android.demon.ui.activity.shop.OrderManagerActivity;
import one.bugu.android.demon.ui.activity.wallet.MyWalletActivity;
import one.bugu.android.demon.ui.dialog.DialogMedal;
import one.bugu.android.demon.ui.refresh.util.DensityUtil;
import one.bugu.android.demon.ui.widget.MedalProgressView;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.MedalUtils;
import one.bugu.android.demon.util.MyTextUtils;
import one.bugu.android.demon.util.OnViewClickListener;
import one.bugu.android.demon.util.ParamUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.ShareImageUtils;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * 我的信息页面
 */
@LKContentView(R.layout.fragment_myinfo)
public class UserInfoFragment extends MyBaseFragment {

    Context context;
    /**
     * 占位 view
     */
    @LKInjectView(R.id.view_info_top)
    private View mViewTop;

    /**
     * 邀请好友
     */
    @LKInjectView(R.id.invite_layout)
    private RelativeLayout inviteLayout;

    /**
     * 订单管理
     */
    @LKInjectView(R.id.gzh_layout)
    private RelativeLayout gzhLayout;

    /**
     * 用户昵称
     */
    @LKInjectView(R.id.tv_user_name)
    private TextView tv_user_name;
    /**
     * 手机号
     */
    @LKInjectView(R.id.tv_user_phone)
    private TextView tv_user_phone;
    /**
     * 用户头像
     */
    @LKInjectView(R.id.iv_user_avatar)
    private ImageView iv_user_avatar;

    /**
     * 我的钱包入口
     */
    @LKInjectView(R.id.rl_wallet_layout)
    private RelativeLayout rl_wallet_layout;

    /**
     * 邀请人数
     */
    @LKInjectView(R.id.invite_num)
    private TextView inviteNum;
    /**
     * 意见反馈
     */
    @LKInjectView(R.id.feedback)
    private RelativeLayout feedback;

    /**
     * 任务中心
     */
    @LKInjectView(R.id.task_layout)
    private RelativeLayout task;
    /**
     * 算力数量
     */
    @LKInjectView(R.id.tv_info_cal_num)
    private TextView tv_info_cal_num;

    /**
     * 添加客服微信
     */
    @LKInjectView(R.id.add_wx_chat)
    private RelativeLayout add_wxRl;

    /**
     * 绑定微信
     */
    @LKInjectView(R.id.weixin_layout)
    private RelativeLayout mWeixinLayout;
    /**
     * 消息数量
     */
    @LKInjectView(R.id.tv_weixin_status)
    private TextView mWeixinStatus;

    /**
     * 当前BGT数量
     */
    @LKInjectView(R.id.tv_cur_bgt_num)
    private TextView tv_cur_bgt_num;

    /**
     * 下一级解锁数量
     */
    @LKInjectView(R.id.tv_bgt_num_hint)
    private TextView tv_bgt_num_hint;
    /**
     * 当前头衔
     */
    @LKInjectView(R.id.tv_bgt_level)
    private TextView tv_bgt_level;
    /**
     * 头衔进度显示
     */
    @LKInjectView(R.id.pb_progressBar)
    private MedalProgressView pb_progressBar;
    /**
     * 用户头衔
     */
    @LKInjectView(R.id.iv_user_medal)
    private ImageView iv_user_medal;
    /**
     * 滑动组件
     */
    @LKInjectView(R.id.sc_progress_view)
    private HorizontalScrollView sc_progress_view;

    /**
     * 设置
     */
    @LKInjectView(R.id.rl_setting)
    private RelativeLayout rl_setting;


    DecimalFormat df = new DecimalFormat("#.#####");
    private DialogMedal dialogMedal;

    private boolean pageHidden = false;


    @Override
    protected void initView() {
        super.initView();
        //解决fragment嵌套出现状态栏异常问题
        StatusBarUtils.getInstance().setFragmentStatusBar(getContext(), mViewTop);

        context = getActivity();

        //设置默认头衔进度
        pb_progressBar.setLayoutViewData(MedalContant.defBgtMedalData, 0, 29);

    }

    @SuppressLint("SetTextI18n")
    private void initUserInfo() {
        //设置用户信息
        //手机号
        tv_user_phone.setText(PreferencesUtil.getInstance().getString(context, Constant.USERTEL) == null ? "" : PreferencesUtil.getInstance().getString(context, Constant.USERTEL));
        //昵称
        String name = PreferencesUtil.getInstance().getString(context, Constant.USER_NAMR);
        tv_user_name.setText(name);
        //用户头像
        LKUtil.getImageLoader().loadRoundImage(PreferencesUtil.getInstance().getString(context, Constant.USER_AVATAR),
                iv_user_avatar, R.mipmap.nongchang_touxiang);
        //算力
        int calNum = PreferencesUtil.getInstance().getInt(getContext(), Constant.CAL_NUM);
        tv_info_cal_num.setText(calNum + "");
        //当前BGT数量
        inviteNum.setText(PreferencesUtil.getInstance().getString(context, Constant.INVITENUM) == null ? "0" : PreferencesUtil.getInstance().getString(context, Constant.INVITENUM) + "人");

        //size等于0时隐藏
        mWeixinStatus.setVisibility(View.GONE);
        mWeixinStatus.setText("12");
    }

    /**
     * 设置头衔
     */
    private void setBgtMedal(UserSmsInfoBean bgtMedal) {
        //设置进度
        pb_progressBar.setLayoutViewData(bgtMedal.getBgtTitle(), Double.parseDouble(bgtMedal.getBgtNum()), 29);
        //当前BGT数量
        String bgtNum = df.format(Double.parseDouble(PreferencesUtil.getInstance().getString(context, Constant.BGTNUM) == null ? "0" : PreferencesUtil.getInstance().getString(context, Constant.BGTNUM)));
        SpannableString bgtStr = MyTextUtils.getInstance().setAutoTextColor("当前BGT  " + bgtNum, "[0-9]{1,}", "#5856D0");
        tv_cur_bgt_num.setText(bgtStr);
        //下一等级解锁
        double dBgtNum = Double.parseDouble(bgtNum);
        List<MedalBean> bgtTitle = bgtMedal.getBgtTitle();
        int nextLevP = 0;
        for (int i = 0; i < bgtTitle.size(); i++) {
            double maxNum = bgtTitle.get(i).getMaxNum();
            double minNum = bgtTitle.get(i).getMinNum();
            if (dBgtNum >= minNum && dBgtNum < maxNum) {
                nextLevP = i;
                //如果最高等级不再当前页面展示, 则滑动一段距离展示最高等级
                if (i > 4) {
                    //滑动一段距离保证最高等级显示
                    final int finalI = i;
                    sc_progress_view.post(new Runnable() {
                        @Override
                        public void run() {
                            sc_progress_view.scrollTo((finalI - 2) * DensityUtil.dp2px(MedalContant.MEDAL_HORIZONTAL_SPACE), 0);
                        }
                    });
                }
                boolean showBgtMedalDialog = MedalUtils.getInstance().isShowBgtMedalDialog(getContext(), i, true);
                if (showBgtMedalDialog) {
                    //显示弹窗ID
                    showBgtMedalDialog(MedalContant.bgtMedalArr[i], bgtTitle.get(i).getTitleName(), i);
                }
                break;
            }
        }
        //头衔显示内容
        int cueP = nextLevP + 1 >= MedalContant.bgtMedalArr.length - 1 ? MedalContant.bgtMedalArr.length - 1 : nextLevP + 1;
        String nextLevel = "BGT达到" + (int) (bgtTitle.get(cueP).getMinNum()) + "可解锁";
        SpannableString levelStr = MyTextUtils.getInstance().setAutoTextColor(nextLevel, "[0-9]{1,}", "#5856D0");
        tv_bgt_num_hint.setText(levelStr);
        //当前头衔
        Drawable drawable = getActivity().getResources().getDrawable(MedalContant.bgtMedalArr[cueP]);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tv_bgt_level.setCompoundDrawables(drawable, null, null, null);
        tv_bgt_level.setText(bgtTitle.get(cueP).getTitleName());
        //头衔
        Drawable levDr = getActivity().getResources().getDrawable(MedalContant.bgtMedalArr[cueP - 1]);
        iv_user_medal.setImageDrawable(levDr);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        pageHidden = hidden;
        if (hidden && dialogMedal != null) {
            dialogMedal.dismiss();
        }
        if (!hidden) {
            getUserSmsNum();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        getUserSmsNum();
        initUserInfo();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1002 && resultCode == Activity.RESULT_OK) {
            //算力值刷新
            String cal_num = data.getStringExtra("CAL_NUM");
            PreferencesUtil.getInstance().putInt(getContext(), Constant.CAL_NUM, Integer.parseInt(cal_num));
            tv_info_cal_num.setText(cal_num);
        }
    }

    /**
     * 获取用户信息 短信,语音,bgt,手机号,邀请人数等数量信息
     */
    public void getUserSmsNum() {
        String token = PreferencesUtil.getInstance().getString(getActivity(), Constant.TOKEN);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("source", "10");
        LKUtil.getHttpManager().postBody(HttpConstant.GETUSERNUM_URL, map, handler);
    }

    /**
     * 获取用户信息的网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<UserSmsInfoBean> handler = new BaseHttpAsycResponceHandler<UserSmsInfoBean>() {

        @Override
        public void onSuccess(UserSmsInfoBean userSmsInfoBean) {
            super.onSuccess(userSmsInfoBean);
            PreferencesUtil.getInstance().putString(context, Constant.USERTEL, userSmsInfoBean.getUserAccount());
            PreferencesUtil.getInstance().putString(context, Constant.BGTNUM, userSmsInfoBean.getBgtNum());
            PreferencesUtil.getInstance().putString(context, Constant.SHORTMESSAGENUM, userSmsInfoBean.getSmsNum());
            PreferencesUtil.getInstance().putString(context, Constant.VOICENUM, userSmsInfoBean.getVoiceNum());
            PreferencesUtil.getInstance().putString(context, Constant.INVITENUM, userSmsInfoBean.getInviteNum());
            PreferencesUtil.getInstance().putInt(context, Constant.IS_BOUND_WECHAT, userSmsInfoBean.getBandWechatFlag());
            //处理数据
            List<MedalBean> bgtTitle = userSmsInfoBean.getBgtTitle();
            for (int i = 0; i < bgtTitle.size(); i++) {
                if (i <= MedalContant.bgtMedalArr.length) {
                    bgtTitle.get(i).setDrawableRes(MedalContant.bgtMedalArr[i]);
                    bgtTitle.get(i).setImageWidth(24);
                    bgtTitle.get(i).setImageHeight(29);
                }
            }
            //设置bgt头衔
            setBgtMedal(userSmsInfoBean);
            //设置用户数据
            initUserInfo();

        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);

        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    @Override
    protected void initEvent() {
        super.initEvent();

        //我的钱包点击事件
        rl_wallet_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.startAty(getActivity(), MyWalletActivity.class);
            }
        });
        //消息
        mWeixinLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.startAty(getContext(), MessageActivity.class);
            }
        });

        //我的算力
        feedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CalculationActivity.class);
                intent.putExtra(Constant.CALCULATION, tv_info_cal_num.getText().toString());
                startActivityForResult(intent, 1002);
            }
        });

        //邀请好友点击事件 跳转邀请好友页面
        inviteLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<ParamUtils.NameValue> parList = ParamUtils.build().put(WebActivity.TITLE, "邀请好友").put(WebActivity.URL, HttpConstant.INVID_URL).create();
                IntentUtils.startAty(getActivity(), WebActivity.class, parList);
            }
        });

        //订单管理
        gzhLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IntentUtils.startAty(getContext(), OrderManagerActivity.class);
            }
        });

        task.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IntentUtils.startAty(getActivity(), TaskCenterActivity.class);
            }
        });

//        预警账户
        add_wxRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.startAty(getContext(), WarnActivity.class);
            }
        });
        //设置
        rl_setting.setOnClickListener(new OnViewClickListener() {
            @Override
            protected void singleClick(View view) {
                IntentUtils.startAty(getContext(), SettingActivity.class);
            }
        });
    }

    /**
     * 显示BGT头衔弹框
     */
    private void showBgtMedalDialog(int levImage, String levTitle, final int level) {
        if (dialogMedal == null) {
            dialogMedal = new DialogMedal(getContext(), R.style.DialogCenter);
        }
        dialogMedal.setDialogBg(R.mipmap.icon_medal_dialog_bgt_bg);
        dialogMedal.setImageRes(levImage);
        dialogMedal.setLevelTitle(levTitle);
        dialogMedal.setStatus(true);
        dialogMedal.setOnGetBtnClick(new DialogMedal.OnGetBtnClick() {
            @Override
            public void onGetBtnClickListener() {
                ShareImageUtils.getInstance().compShareImage(getActivity(), dialogMedal);
            }
        });
        dialogMedal.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                MedalUtils.getInstance().saveMedalLevStatus(getContext(), level, true);
            }
        });
        if (!dialogMedal.isShowing() && !pageHidden) {
            dialogMedal.show();
        }
    }

}
